define(function(require , exports , module){
	require("ztree-css");
	require("ztree");

	angular.module("uiZtree" , [])
	.directive('uiZtree' , ["$timeout" , "App" , "baseService" , function($timeout , App , baseService){
		return {
			restrict: 'A',
			replace: true,
			link:function($scope , $element , $attrs){
				$timeout(function(){
					var id = $attrs["id"];
					var dataUrl = $attrs["url"];
					var click = $attrs["click"];
					var drag  = $attrs["drag"];
					var nameKey = $attrs["nameKey"]?$attrs["nameKey"]:"name";
					var checked = $attrs["checked"]?true:false;
					var filter = $attrs["filter"];

					baseService.request(dataUrl , "GET")
					.then(function(datas){
			        	var setting = {
			        			check:{
			        				enable:checked
			        			},
			        			data: {
			        				key:{
			        					name:nameKey,
			        					checked:"checked"
			        				},
			        				simpleData: {
			        					enable: true,
			        					idKey:'id',
			        					pIdKey:'parentId',
			        					rootPId:null
			        				}
			        			},
			        			callback:{
			        					onClick:$scope.$eval(click)	
			        			}
			        	};

			        	if (filter) {
			        		var filterFun = $scope.$eval(filter);
			        		for (var i = 0, len = datas.length;i < len;i++) {
			        			filterFun(datas[i]);
			        		}
			        	}
			        
			        	$scope.tree = datas;		
						$.fn.zTree.init($element, setting , datas);
						var tree = $.fn.zTree.getZTreeObj(id);
						
						if ($scope.selectTreeId) {
							var selectedTree = tree.getNodeByTId($scope.selectTreeId);
							if (selectedTree) {
								tree.selectNode(selectedTree , true);
								var parent = selectedTree.getParentNode();
								while (parent) {
									tree.expandNode(parent , true , true , true);
									parent = parent.getParentNode();
								}
							}
						}
						
					});	
				});
			}
		};
	}]);
});